﻿using System.Configuration;
using System.Data;
using System.Windows;

namespace K9Tools;

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App
{
    protected override void OnStartup(StartupEventArgs e)
    {
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

        try
        {
            base.OnStartup(e);
        }
        catch (Exception ex)
        {
            //if (exception is Prism.Ioc.ContainerResolutionException iocEx)
            //{
            //    Log.Fatal("程序失败：" + iocEx.GetRootException());
            //}
            //else
            //{
            //    Log.Fatal("程序失败：" + exception);
            //}
            MessageBox.Show("程序启动是发生意外错误，即将退出: " + ex.Message, "K9");
            Shutdown(-1);
        }
    }

    private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        // Log.Error(e.ExceptionObject as Exception, "意外错误");
        if (e.IsTerminating)
        {
            MessageBox.Show("程序发生意外错误，即将退出: " + (e.ExceptionObject as Exception)?.Message, "K9");
        }
    }

    protected override Window CreateShell()
    {
        return Container.Resolve<Views.MainWindow>();
    }

    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {

    }

    protected override IModuleCatalog CreateModuleCatalog()
    {
        var pluginsPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins");
#if DEBUG
        if (!System.IO.Directory.Exists(pluginsPath))
        {
            var parent = System.IO.Directory.GetParent(pluginsPath);
            while (true)
            {
                if (parent == null) break;
                if (System.IO.File.Exists(System.IO.Path.Combine(parent.FullName, "K9Tools.csproj")))
                {
                    pluginsPath = System.IO.Path.Combine(parent.FullName, "Plugins");
                    break;
                }
                parent = parent.Parent;
            }
        }
#endif
        var directoryModuleCatalog = new DirectoryModuleCatalog() { ModulePath = pluginsPath };
        return directoryModuleCatalog;
    }

    protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
    {
        moduleCatalog.AddModule<Core.CoreModule>();
    }
}

